package com.lw.leetcode.tree.b;

import com.lw.leetcode.tree.TreeNode;

import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * 6018. 根据描述创建二叉树
 *
 * @author liw
 * @version 1.0
 * @date 2022/3/6 20:23
 */
public class CreateBinaryTree {

    public TreeNode createBinaryTree(int[][] descriptions) {
        Map<Integer, TreeNode> nodeMap = new HashMap<>();
        Map<Integer, Boolean> flagMap = new HashMap<>();
        for (int[] description : descriptions) {
            int p = description[0];
            int t = description[1];
            int f = description[2];
            TreeNode pn = nodeMap.get(p);
            if (pn == null) {
                pn = new TreeNode(p);
                nodeMap.put(p, pn);
            }
            TreeNode tn = nodeMap.get(t);
            if (tn == null) {
                tn = new TreeNode(t);
                nodeMap.put(t, tn);
            }
            if (f == 0) {
                pn.right = tn;
            } else {
                pn.left = tn;
            }
            flagMap.put(t, true);
            if (!flagMap.containsKey(p)) {
                flagMap.put(p, null);
            }
        }
        for (Map.Entry<Integer, Boolean> entry : flagMap.entrySet()) {
            if (entry.getValue() == null) {
                return nodeMap.get(entry.getKey());
            }
        }
        return null;
    }

}
